package com.situ.student.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.student.entity.User;

public class LoginFilter implements Filter {
	
	public LoginFilter() {
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//判断有没有登陆，没有登陆重定向到登陆界面
		//登陆上chaing.dofile
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		String uri = httpServletRequest.getRequestURI();
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("uri : " + uri);
		System.out.println("servletPath" + servletPath);
		
		int lastIndex = servletPath.lastIndexOf(".");
		String extension = "";
		if (lastIndex != -1) {
			extension = servletPath.substring(lastIndex);
		}
		
		if ("/login.jsp".equals(servletPath)
				|| "/user_register.jsp".equals(servletPath)
				|| "/checkImg".equals(servletPath)
				|| "/login".equals(servletPath)
				|| ".js".equals(extension)
				|| ".css".equals(extension)
				|| ".png".equals(extension)) {
			chain.doFilter(request, response);
		}else {//验证
			//判断用户有没有登陆
			HttpSession session = httpServletRequest.getSession();//建立session
			User user = (User) session.getAttribute("user");
			if (user == null) {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp");
				return;
			}
			//下一个过滤器或放行
			chain.doFilter(request, response);
		}
		//chain.doFilter(request, response); //打开拦截关闭这个，关闭拦截打开这个
	}

	@Override
	public void destroy() {
		
	}

}
